package service

import (
	"context"
	"gorm.io/gorm"
	"log"
	"mytest/database"
	"mytest/kitcli/user/pkg/model"
	"mytest/kitcli/user/pkg/transport/grpc/pb"
)

// UserService describes the service.
type UserService interface {
	GetUserList(ctx context.Context, request *pb.GetUserListRequest) (result interface{}, err error)
	AddUser(ctx context.Context, request *pb.AddUserRequest) (result interface{}, err error)
	UpdateUser(ctx context.Context, request *pb.UpdateUserRequest) (result interface{}, err error)
	DeleteUser(ctx context.Context, request *pb.DeleteUserRequest) (result interface{}, err error)
	FindUser(ctx context.Context, request *pb.FindUserRequest) (result interface{}, err error)
}

type basicUserService struct{}

func (b *basicUserService) GetUserList(ctx context.Context, request *pb.GetUserListRequest) (result interface{}, err error) {
	response := &pb.GetUserListReply{}

	var users []*model.User
	var condition string
	condition = GenerateQueryCondition(request.Condition)

	flag := false

	if flag {
		var total int64
		if err = database.DB.Model(model.User{}).Where(condition).Count(&total).Error; err != nil {
			response.Code = 0
			response.Msg = "get data failed"
			log.Printf("查询用户列表失败: %s \n", err.Error())
			return response, err
		}
		offset := request.Page.PageSize * (request.Page.Page - 1)
		if err = database.DB.Debug().Where(condition).Offset(int(offset)).Limit(int(request.Page.PageSize)).Order("id desc").Find(&users).Error; err != nil {
			response.Code = 0
			response.Msg = "get data failed"
			log.Printf("查询用户列表失败: %s \n", err.Error())
			return response, err
		}
	} else {
		var user model.User
		users, err = user.GetList(condition, int(request.Page.Page), int(request.Page.PageSize))
	}
	var userList []*pb.UserInfo

	if len(users) > 0 {
		for _, v := range users {
			userinfo := &pb.UserInfo{
				Id:   v.Id,
				Name: v.Name,
				Age:  v.Age,
			}
			userList = append(userList, userinfo)
		}
	}

	response.UserList = userList

	response.Code = 1
	response.Msg = "success"

	return response, err
}
func (b *basicUserService) AddUser(ctx context.Context, request *pb.AddUserRequest) (result interface{}, err error) {
	var response = &pb.AddUserReply{}
	response.Code = 1
	response.Msg = "success"
	err = database.DB.Debug().Create(&model.User{Name: request.Name, Age: request.Age}).Error
	if err != nil {
		response.Code = 0
		response.Msg = "add user failed"
	}
	return response, err
}
func (b *basicUserService) UpdateUser(ctx context.Context, request *pb.UpdateUserRequest) (result interface{}, err error) {
	var response = &pb.UpdateUserReply{}
	response.Code = 1
	response.Msg = "success"
	id := request.Id
	var user model.User
	err = database.DB.Debug().Model(model.User{}).Where("id = ?", id).First(&user).Error
	if err != nil && err == gorm.ErrRecordNotFound {
		response.Code = 0
		response.Msg = "update user failed"
		return response, err
	}
	data := map[string]interface{}{
		"name": request.Name,
		"age":  request.Age,
	}
	err = database.DB.Debug().Model(model.User{}).Where("id = ?", id).Updates(data).Error
	if err != nil {
		response.Code = 0
		response.Msg = "update user failed"
	}
	return response, err
}
func (b *basicUserService) DeleteUser(ctx context.Context, request *pb.DeleteUserRequest) (result interface{}, err error) {
	// TODO implement the business logic of DeleteUser
	var response = &pb.DeleteUserReply{}
	response.Code = 1
	response.Msg = "success"
	id := request.Id
	err = database.DB.Debug().Where("id=?", id).Delete(model.User{}).Error
	if err != nil {
		response.Code = 0
		response.Msg = "delete user failed"
	}
	return response, err
}

func (b *basicUserService) FindUser(ctx context.Context, request *pb.FindUserRequest) (result interface{}, err error) {
	var response = &pb.FindUserReply{}
	response.Code = 1
	response.Msg = "success"
	var user model.User
	conditions := GenerateQueryCondition(request.Condition)
	err = database.DB.Debug().Model(model.User{}).Where(conditions).First(&user).Error
	if err != nil {
		response.Code = 0
		response.Msg = "find user failed"
		return response, err
	}
	response.Code = 0
	response.Msg = "success"
	userinfo := &pb.UserInfo{
		Id:   user.Id,
		Name: user.Name,
		Age:  user.Age,
	}
	response.Userinfo = userinfo
	return response, err
}

// NewBasicUserService returns a naive, stateless implementation of UserService.
func NewBasicUserService() UserService {
	return &basicUserService{}
}

// New returns a UserService with all of the expected middleware wired in.
func New(middleware []Middleware) UserService {
	var svc UserService = NewBasicUserService()
	for _, m := range middleware {
		svc = m(svc)
	}
	return svc
}
